package com.dt.platform.ops.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.github.foxnic.commons.log.Logger;
import com.mysql.jdbc.log.Log;


import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


public class MonitorDataProcessPingExecutor {

    public static ThreadPoolExecutor executor = null;

    public static void addTask(MonitorDataProcessPingUtil pm){
        if(executor==null){
            int corePoolSize=300;
            int maxPoosSize=10000;
            int keepAliaveTime=60;
            executor=new ThreadPoolExecutor(corePoolSize,maxPoosSize, keepAliaveTime,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(100),
                    new SimpleNamedThreadFactory(),
                    new ThreadPoolExecutor.AbortPolicy());
            Logger.info("create thread pool,corePoolSize:"+corePoolSize+",maxPoosSize:"+maxPoosSize+",keepAliaveTime:"+keepAliaveTime);
        }
        Logger.info("add task,node:"+pm.getNode().getNodeNameShow()+",indicator code:"+pm.getIndicator().getCode());
        executor.submit(new Task(pm));
    }

    static class Task implements Runnable {
        private MonitorDataProcessPingUtil pmInst;
        public Task( MonitorDataProcessPingUtil pm) {
            this.pmInst=pm;
        }
        @Override
        public void run() {
            pmInst.PingService();
        }
    }

    static class TaskTest implements Runnable {

        public TaskTest(){}
        @Override
        public void run() {
            System.out.println("this is test");
        }
    }
    public static void addTaskTest(){
        if(executor==null){
            int corePoolSize=3;
            int maxPoosSize=10;
            int keepAliaveTime=60;
            executor=new ThreadPoolExecutor(corePoolSize,maxPoosSize, keepAliaveTime,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(2),
                    new SimpleNamedThreadFactory(),
                    new ThreadPoolExecutor.AbortPolicy());
            Logger.info("create thread pool,corePoolSize:"+corePoolSize+",maxPoosSize:"+maxPoosSize+",keepAliaveTime:"+keepAliaveTime);
            queryPoolStatus();
        }
        executor.submit(new TaskTest());
    }


    public static void main(String[] args) {
        for(int i=0;i<2;i++){
            MonitorDataProcessPingExecutor.addTaskTest();
            MonitorDataProcessPingExecutor.queryPoolStatus();
        }

    }
    static class SimpleNamedThreadFactory implements ThreadFactory {
        private static final AtomicInteger poolNumber = new AtomicInteger(1);
        // 线程组（可选）
        private final ThreadGroup group;
        // 线程名前缀
        private final String namePrefix;
        // 线程编号（用于区分同一工厂创建的不同线程）
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        public SimpleNamedThreadFactory() {
            // 获取系统安全管理器，如果存在则使用其线程组，否则使用当前线程的线程组
            SecurityManager s = System.getSecurityManager();
            group = (s != null) ? s.getThreadGroup() :
                    Thread.currentThread().getThreadGroup();
            // 设置线程名前缀，包含池编号
            namePrefix = "Ping线程池-" + poolNumber.getAndIncrement() + "-thread-";
        }

        @Override
        public Thread newThread(Runnable r) {
            // 创建新线程，并设置名称
            Thread t = new Thread(group, r,
                    namePrefix + threadNumber.getAndIncrement(),
                    0); // 栈大小，0表示忽略该参数
            // 确保创建的线程不是守护线程
            if (t.isDaemon()) {
                t.setDaemon(false);
            }
            // 设置统一的线程优先级（普通优先级）
            if (t.getPriority() != Thread.NORM_PRIORITY) {
                t.setPriority(Thread.NORM_PRIORITY);
            }
            return t;
        }
    }
    public static JSONObject queryPoolStatus(){
        JSONObject poolStatus=new JSONObject();
        if(executor==null){
            Logger.info("当前线程池未初始化");
        }else{
            poolStatus.put("poolSize",executor.getPoolSize());
            poolStatus.put("activeCount",executor.getActiveCount());
            poolStatus.put("completedTaskCount",executor.getCompletedTaskCount());
            poolStatus.put("taskCount",executor.getTaskCount());
            poolStatus.put("queueSize",executor.getQueue().size());
            poolStatus.put("largestPoolSize",executor.getLargestPoolSize());
            Logger.info("pool status:"+poolStatus.toJSONString());
        }
        return poolStatus;
    }
    public static void shutdown(){
         if(executor!=null){
            executor.shutdown(); // 启动有序关闭，不再接受新任务
            try {
                // 等待现有任务终止，最多等待60秒
                if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                    System.err.println("Ping线程池未在超时时间内完全关闭，尝试强制关闭...");
                    executor.shutdownNow(); // 尝试取消所有正在执行的任务
                }
            } catch (InterruptedException e) {
                executor.shutdownNow();
                Thread.currentThread().interrupt();
            }

        }else {
            Logger.info("当前线程池未初始化");
        }
    }
}


